package exquery.util

import org.apache.log4j.Logger
import setupx.entity.ClassOrgan

/**
 * User: pradeep
 * Date: Nov 30, 2010
 * Time: 8:20:43 PM
 * common utility methods
 */
class CommonUtil {
  Logger gLogger = Logger.getInstance(CommonUtil.class)
  private static  CommonUtil instance = null

    /**
     * returns the instance
     * @return
     */
  public static  CommonUtil getInstance() {
    if (instance == null) {
      instance = new  CommonUtil()
    }

    return instance
  }

    /**
     * to create list of items from comma, tab, single white space and new line separated text
     * @param Ids
     * @return
     */
  def prepareSearchableIdList(def Ids){
    gLogger.info "Coming into prepareSearchableIdList method of CommonUtil"
    def resultIds
    if(Ids!=null && Ids.toString().trim().length()>0){
      if(Ids instanceof String){
        def temp
        if(Ids.toString().indexOf("\n") != -1 && Ids.toString().split("[\n]").size() >0 ){
          temp = Ids.toString().split("[\n]")
        }else
        if(Ids.toString().indexOf(",") != -1 && Ids.toString().split(",").size() >0 ){
          temp = Ids.toString().split(",")
        }else
        if(Ids.toString().indexOf("\t") != -1 && Ids.toString().split("[\t]").size() >0 ){
          temp = Ids.toString().split("[\t]")
        }else
        if(Ids.toString().indexOf(" ") != -1 && Ids.toString().split(" ").size() >0 ){
          temp = Ids.toString().split(" ")
        }

        resultIds = []
        if(temp!=null){
          temp.each {id->
            resultIds.add id?.toString().trim()
          }
        }else{
          resultIds = []
          resultIds.add Ids
        }
      }else{
        resultIds = []
        resultIds.add Ids
      }
    }
    gLogger.info "resultIds :: ${resultIds}"
    gLogger.info "Out from prepareSearchableIdList method of CommonUtil"
    return resultIds
  }

    /**
     * To get object map for Samples Extraction
     * @return
     */
  def getSXObjectType(){
    def sxObjectType = [[ID:"experiments",VALUE:"Experiments"],[ID:"classes",VALUE:"Classes"],[ID:"samples",VALUE:"Samples"],[ID:"chromatofs",VALUE:"Chromatofs"]]
    return sxObjectType

  }

    /**
     * To get object map for Search
     * @return
     */
  def getSXSearchObjectType(){
    def sxSearchObjectType = [[ID:"SearchAll",VALUE:"-- All --"],[ID:"Experiments",VALUE:"Experiments"],[ID:"Classes",VALUE:"Classes"],[ID:"Samples",VALUE:"Samples"],[ID:"Species",VALUE:"Species"],[ID:"Organs",VALUE:"Organs"],[ID:"User",VALUE:"Collaboration or Owner"]]
    return sxSearchObjectType

  }

    /**
     * Prepare list of organs as String
     * @param organsSet
     * @return
     */
  def prepareOrgansText(def organsSet){
      //organsSet = experimentClass?.organSet
      def organsName = ""
      if( organsSet != null ){

          organsSet.each {ClassOrgan organ->
          if( organsName.toString().length() == 0 ){
              organsName = organ.getOrgan_name()
          }else{
              if(!organsName.contains(organ.getOrgan_name())){
                organsName += "; " + organ.getOrgan_name()
              }
          }
        }

      }
      return organsName;
  }

  /**
     * Prepare list of organs as String
     * @param organsSet
     * @return
     */
  def prepareOrgansTissueText(def organsSet){
      //organsSet = experimentClass?.organSet
      def organsName = ""
      if( organsSet != null ){

          organsSet.each {ClassOrgan organ->
          if( organsName.toString().length() == 0 ){
              organsName = organ.getTissue()
          }else{
              if(!organsName.contains(organ.getTissue())){
                organsName += "; " + organ.getTissue()
              }
          }
        }

      }
      return organsName;
  }

  /**
     * Prepare list of organs as String
     * @param organsSet
     * @return
     */
  def prepareOrgansCellTypeText(def organsSet){
      //organsSet = experimentClass?.organSet
      def organsName = ""
      if( organsSet != null ){

          organsSet.each {ClassOrgan organ->
          if( organsName.toString().length() == 0 ){
              organsName = organ.getCell_type()
          }else{
              if(!organsName.contains(organ.getCell_type())){
                organsName += "; " + organ.getCell_type()
              }
          }
        }

      }
      return organsName;
  }

  /**
     * Prepare list of organs as String
     * @param organsSet
     * @return
     */
  def prepareOrgansSubcellularCelltype(def organsSet){
      //organsSet = experimentClass?.organSet
      def organsName = ""
      if( organsSet != null ){

          organsSet.each {ClassOrgan organ->
          if( organsName.toString().length() == 0 ){
              organsName = organ.getSubcellular_celltype()
          }else{
              if(!organsName.contains(organ.getSubcellular_celltype())){
                organsName += "; " + organ.getSubcellular_celltype()
              }
          }
        }

      }
      return organsName;
  }

    /**
     * Prepare list of species as String
     * @param speciesSet
     * @return
     */
  def prepareSpeciesText(def speciesSet){
      //organsSet = experimentClass?.organSet
      def speciesName = ""
      if( speciesSet != null ){

          speciesSet.each { species->
          if( speciesName.toString().length() == 0 ){
              speciesName = species.getSpecies_name()
          }else{
              speciesName += "; " + species.getSpecies_name()
          }
        }

      }
      return speciesName;
  }

    /**
     * Prepare list of User as String
     * @param experimentUserRights
     * @return
     */
  def prepareOwnersTextFromExpRights(def experimentUserRights){

      gLogger.info("experimentUserRights ::${experimentUserRights}")

      def ownersName = ""
      if( experimentUserRights != null ){
          def displayName = ""
          experimentUserRights.sort{it.secUser.displayname}.each { user->
            displayName = user?.secUser.getDisplayname()
            //gLogger.info "displayName :: ${displayName}"
            if( displayName!=null && displayName.toString().trim().length() != 0 && !displayName.toString().trim().equalsIgnoreCase("Master Account (SX)")
                    && !displayName.toString().trim().equalsIgnoreCase("System Admin") && !displayName.toString().trim().equalsIgnoreCase("public") ){
                if( ownersName.toString().length() != 0 ){
                  ownersName += "; "
                }

                if(user?.secUser.getEmail()!=null && user?.secUser.getEmail().trim().length()>0){
                  ownersName += "<span><a href=\"mailto:${user?.secUser.getEmail()}\" title=\"click to send a mail\">${user?.secUser.getDisplayname()}</a></span>"
                }else{
                  ownersName += "<span>${user?.secUser.getDisplayname()}</span>"
                }

            }
          }
      }

      return ownersName;
  }

    /**
     * Encode Text as HTML Format
     * @param inputStr
     * @return
     */
  def customEncodeAsHTML(def inputStr){
     def outputStr=""

     if(inputStr!=null && inputStr.toString().trim().length()>0){
         outputStr = "<p>"

         if(inputStr.toString().contains("\n")){
           outputStr += inputStr.toString().encodeAsHTML().replaceAll("\n","</p><p>");
         }else{
           outputStr += inputStr.toString().encodeAsHTML()
         }

         outputStr += "</p>"
     }
     return outputStr
  }

    /**
     * Prepare list of Chromatofs as String
     * @param chromatofSet
     * @return
     */
  def prepareChromatofsString(def chromatofSet){
      String chromatofIds = "";
      if( chromatofSet != null ){

          chromatofSet.each { chromatof->
          if( chromatofIds.toString().length() == 0 ){
              chromatofIds = chromatof.getChromatofFileId()
          }else{
              chromatofIds += "; " + chromatof.getChromatofFileId()
          }
        }
      }
      return chromatofIds;
  }

  /**
   * cast the list if String data into Upper Case 
   * @param list
   * @return
   */
  def toUpper(def list){
      def resultList

      if(list!=null){
          if(list instanceof Collection){
              resultList = []
              list.each {data->
                  resultList.add(data.toString().toUpperCase())
              }
          }else if (list instanceof String[]){
              resultList = new String[list.size()]
              list.eachWithIndex { data,index->
                  resultList[index] = data.toString().toUpperCase()
              }
          }else{
             resultList = list.toString().toUpperCase()
          }
      }
     return resultList
  }

  /**
   * cast the list if String data into Lower Case 
   * @param list
   * @return
   */
  def toLower(def list){
      def resultList

      if(list!=null){
          if(list instanceof Collection){
              resultList = []
              list.each {data->
                  resultList.add(data.toString().toLowerCase())
              }
          }else if (list instanceof String[]){
              resultList = new String[list.size()]
              list.eachWithIndex { data,index->
                  resultList[index] = data.toString().toLowerCase()
              }
          }else{
             resultList = list.toString().toLowerCase()
          }
      }
     return resultList
  }

  /**
   * convert list of string data into semi collon 
   * @param nameList
   * @return
   */
  def convertNameListIntoString(def nameList){
        //gLogger.info "nameList :: ${nameList}"
        String nameStr=""

        if(nameList!=null){
            if(nameList instanceof Collection<String>){
                nameList.each {name->
                    if(nameStr.trim().length()==0){
                       nameStr = name
                    }else{
                       nameStr += "; "+name
                    }
                }
            }else if (nameList instanceof String[]){
                nameList.each {name->
                    if(nameStr.trim().length()==0){
                       nameStr = name
                    }else{
                       nameStr += "; "+name
                    }
                }
            }else{
               nameStr = nameList.toString()
            }
        }

        return nameStr
    }

  /**
   * to prepare distinct list of text
   * @param list
   * @return
   */
  def getDistinctList(def list){
      def resultList

      if(list!=null){
          def temp 
          if(list instanceof Collection){
              resultList = []
              temp=[]
              list.each {data->
                  if( !temp.contains(data.toString().toLowerCase()) ){
                    temp.add(data.toString().toLowerCase())
                    resultList.add(data.toString())
                  }
              }
          }else if (list instanceof String[]){
              def tempResultList = []
              temp=[]
              list.each {data->
                  if( !temp.contains(data.toString().toLowerCase()) ){
                    temp.add(data.toString().toLowerCase())
                    tempResultList.add(data.toString())
                  }
              }
              if(tempResultList!=null && tempResultList.size()>0){
                resultList = new String[tempResultList.size()]
                tempResultList.eachWithIndex { data,index->
                    resultList[index] = data.toString().toLowerCase()
                }
              }
         }else{
             resultList = list.toString().toLowerCase()
          }
      }
     return resultList
  }  
}
